<?php
class ModelCatalogAttributeGroup extends Model {
	public function addAttributeGroup($data) {
		$this->db->query("INSERT INTO  @@attribute_group SET sort_order = " . (int)$data['sort_order']);

		$attribute_group_id = $this->db->getLastId();

		foreach ($data['attribute_group_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO  @@attribute_group_description SET attribute_group_id = " . (int)$attribute_group_id . ", language_id = " . (int)$language_id . ", name = '" . ES($value['name']) . "'");
		}
	}

	public function editAttributeGroup($attribute_group_id, $data) {
		$this->db->query("UPDATE  @@attribute_group SET sort_order = " . (int)$data['sort_order'] . " WHERE attribute_group_id = " . (int)$attribute_group_id);

		$this->db->query("DELETE FROM  @@attribute_group_description WHERE attribute_group_id = " . (int)$attribute_group_id);

		foreach ($data['attribute_group_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO  @@attribute_group_description SET attribute_group_id = " . (int)$attribute_group_id . ", language_id = " . (int)$language_id . ", name = '" . ES($value['name']) . "'");
		}
	}

	public function deleteAttributeGroup($attribute_group_id) {
		$this->db->query("DELETE FROM  @@attribute_group WHERE attribute_group_id = " . (int)$attribute_group_id);
		$this->db->query("DELETE FROM  @@attribute_group_description WHERE attribute_group_id = " . (int)$attribute_group_id);
	}

	public function getAttributeGroup($attribute_group_id) {
		return $this->db->queryOne("SELECT * FROM  @@attribute_group WHERE attribute_group_id = " . (int)$attribute_group_id);
	}

	public function getAttributeGroups($filter = null) {
		$sql = "SELECT * FROM  @@attribute_group ag LEFT JOIN  @@attribute_group_description agd ON (ag.attribute_group_id = agd.attribute_group_id) WHERE agd.language_id = " . (int)C('config_language_id');

		if ($filter != null) {
			if ($filter->get('filter_name')) {
				$sql .= " AND agd.name LIKE '" . ES($filter->get('filter_name')). "%'";
			}
			
			$sql .= $filter->sort('agd.name');			
			$sql .= $filter->limit();
		}
		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getAttributeGroupDescriptions($attribute_group_id) {
		$attribute_group_data = array();

		$query = $this->db->query("SELECT * FROM  @@attribute_group_description WHERE attribute_group_id = " . (int)$attribute_group_id);

		foreach ($query->rows as $result) {
			$attribute_group_data[$result['language_id']] = array('name' => $result['name']);
		}

		return $attribute_group_data;
	}

	public function getTotalAttributeGroups() {
      	return $this->db->queryOne("SELECT COUNT(*) AS total FROM  @@attribute_group");
	}
}
?>